package com.dxy.netty.jsonserialize;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Description JSON序列化 netty客户端
 * @Author dangxianyue
 * @Date 2023/1/8 15:33
 */
public class JsonSerializeNettyClient {

    /** 主机和端口 */
    private final String host;
    private final int port;

    /**
     * @description 构造器
     * @author xiao tang
     * @date 2022/9/3
     */
    public JsonSerializeNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new JsonSerializeNettyClient("127.0.0.1", 6668).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() throws InterruptedException {
        // 客户端需要一个事件循环组
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            // 创建客户端启动对象， 注意是 BootStrap
            Bootstrap bootstrap = new Bootstrap();
            // 设置相关参数
            bootstrap.group(eventLoopGroup) // 设置线程组
                    .channel(NioSocketChannel.class) // 设置客户端通道实现类(反射)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加客户端出战编码器
                            pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                            // 添加客户端入站解码器
                            pipeline.addLast(new RpcDecoder(RpcResponse.class, new JSONSerializer()));
                            // 添加业务处理器
                            pipeline.addLast(new JsonSerializeNettyClientHandler()); // 加入自己的处理器
                        }
                    });
            System.out.println("client is ok");
            // 启动客户端去连接服务器
            // ChannelFuture， 设计到netty的异步模型
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();
            // 给关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
